layui.use(['tableEdit', 'table', 'form', 'laydate',"selectInput","excel"], function () {
    let layer = layui.layer //弹层
        , table = layui.table //表格
        , form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        excel = layui.excel,
        selectInput = layui.selectInput;
    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });
    function getAllJson(jsons) {
        let tmpitem=[]
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el,name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon:true,
                indent: 20,
                expandedKeys:false
            },
            height: 'auto',
            data: data,
            on: function ({ arr, change, isAdd }) {
                return this
            }
        })
    }
    setCustomerInfo("")
    function setCustomerInfo(initData) {
        //客户名称
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })
        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            $.ajax({
                url: "basicInformation/getCustomerInfo?info=" + obj.value,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        customerInfo = res.data.customerInfo;
                        for (let i in customerInfo) {
                            customerInfo[i]["value"] = customerInfo[i].code;
                            tempData.push(customerInfo[i]);
                        }
                    }
                }
            })
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            let name = obj.textContent;
            $("#customerCode").val(code);
            $("#customerName").val(name);
            //获取客户联系人
            getCustomerContactName(code);
            //获取客户等级
            $("#customerLevelName").val("");
            $("#customerLevelCode").val("");
            for(let i in customerInfo){
                if(customerInfo[i].code == code){
                    let customerLevelName = customerInfo[i]["customerLevelName"];
                    let customerLevelCode = customerInfo[i]["customerLevelCode"];
                    if(!isEmpty(customerLevelName)){
                        $("#customerLevelName").val(customerLevelName);
                        $("#customerLevelCode").val(customerLevelCode);
                        break;
                    }
                }
            }
        });
    }

    let salesmanList=[];
    let deptList = [];
    (function () {
        let treeList = getCurrentDepartmentUser();
        if(treeList && treeList.list){
            let operationTree = getAllJson(treeList.list);
            salesmanList= getxmselect("#salesmanCode","salesmanCode", operationTree)
        }else {
            salesmanList=getxmselect("#salesmanCode","salesmanCode", [])
        }

        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptList = getxmselect("#departmentCode", "departmentCode", deptTree);
        } else {
            deptList = getxmselect("#departmentCode", "departmentCode", [{name: user.name, value: user.code}]);
        }
    })()

        //获取所有公司信息
        $.ajax({
            url:"receivePayment/getCompanyInfo",
            success:function(data){
                if(data.status == 200){
                    for(let i in data.data){
                        //公司名称
                        $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取币种
        $.ajax({
            url:"receivePayment/getCurrencyInfo",
            success:function(data){
                if(data.status == 200){
                    for(let i in data.data){
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });



        //获取所有银行名称
        $.ajax({
            url:'billing/getAllBankName',
            success:function(data){
                if(data.status==200){
                    for (let i in data.data){
                        baneName=data.data;
                        $("#bankName").append("<option value=\"" + data.data[i] + "\">" + data.data[i] + "</option>");
                    }
                    form.render('select');
                }
            }
        });


    form.render();//表单刷新
    let initData = [];
    table.render({
        elem: '#collection4Select'
        ,data:initData
        ,toolbar: '#collection4Toolbar'
        ,totalRow: true
        ,cols: [[
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            , {field:'contractNo', title:'外销合同号',sort:true,width: 200, align: 'center',event:'contractNo'}
            , {field:'signingDateStr', title:'签约日期',sort:true,width: 150, align: 'center'}
            , {field: 'salesmanName', title: '业务员', sort: true, width: 150, align: 'center'}
            , {field: 'customerName', title: '客户名称', sort: true, width: 150, align: 'center'}
            , {field:'contractCurrency', title:'合同币种',sort:true,width: 150, align: 'center'}
            , {field:'totalContractAmount', title:'合同应收金额',sort:true,width: 150, align: 'center', totalRow: true}
            , {field:'currency', title:'收款币种',sort:true,width: 150, align: 'center'}
            , {field:'receivableUSD', title:'应收货款(USD)',sort:true,width: 160, align: 'center', totalRow: true}
            , {field:'receivableRMB', title:'应收折人民币',sort:true,width: 160, align: 'center', totalRow: true}
            , {field:'receivedUSD', title:'已收货款(USD)',sort:true,width: 160, align: 'center', totalRow: true,event:'receivedUSD'}
            , {field:'receivedRMB', title:'以折收人民币',sort:true,width: 160, align: 'center', totalRow: true}
            , {field: 'uncollectedUSD', title: '未收货款(USD)', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'uncollectedRMB', title: '未收折人民币', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'foreignBankDeductionsUSD', title: '国外银行扣费（USD）', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'foreignBankDeductionsRMB', title: '国外银行扣费折人民币', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'compensateUSD', title: '赔偿客户(USD)', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'compensateRMB', title: '赔偿客户折人民币', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'actualReceivedUSD', title: '实收货款(USD)', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'actualReceivedRMB', title: '实收折人民币', sort: true, width: 160, align: 'center', totalRow: true}
            , {field: 'signingCompanyName', title: '公司名称', sort: true, width: 200, align: 'center'}
            , {field: 'bankName', title: '银行名称', sort: true, width: 200, align: 'center'}
        ]]
        ,id: 'maininformationtableid'
        ,height: $(document).height() - $('#collection4Select').offset().top - 75,
        //开启分页
        page: true,
        limits: [300,600,900],
    });

    table.on('tool(collection4Table)', function(obj){
        let data = obj.data;
        //外销合同号编号
        let contractNo = data.contractNo;
        if (obj.event === 'contractNo' || obj.event ==='receivedUSD'){
            parent.detab("views/jsp/Money/collection.jsp");
            parent.intab("views/jsp/Money/collection.jsp?contractNo="+contractNo, "收款");
        }
    });


    //搜索提交
    form.on('submit(submitform)', function(data){
        /*let operationCode = data.field.operationCode;
        if(operationCode==""){
            data.field.operationCode =user.code;
        }*/
        table.reload('maininformationtableid', {
            page: {
                limit:300,
                curr: 1
            },
            url:'receivePayment/collectionStatistics4ListByPage',
            where:  data.field
        }, 'data');
        return false;
    });


    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"receivePayment/getContractStatisticsFourthExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 150,
                        'AH': 150
                    }, 150);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '按合同应收款统计.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });



    document.getElementById('clear').onclick = function(){
        salesmanList.setValue([ ]);
        deptList.setValue([ ]);
    };
});



